<?php

namespace Forwzb\Yii2Api\helper;

use DateTime;
use DateTimeZone;
use Yii;
use yii\base\BaseObject;
use yii\base\InvalidConfigException;
use yii\di\NotInstantiableException;

/**
 * 时区识别组件
 */
class TimezoneParser extends BaseObject
{
    public $timezone; // 用于存储时区的属性
    public $header = 'timezone';

    public function init()
    {
        parent::init();
        $this->timezone = Yii::$app->timeZone;
        $this->detectSetTimezone();
    }

    function isValidTimezone($timezone)
    {
        try {
            new DateTimeZone($timezone);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    protected function detectSetTimezone()
    {
        $request = Yii::$app->getRequest();
        $headers = $request->getHeaders();

        // 检查请求头中是否包含 timezone 参数
        if ($headers->has($this->header)) {
            $timezone = $headers->get($this->header);

            if ($this->isValidTimezone($timezone)) {
                // 这里可以添加验证时区合法性的逻辑
                $this->timezone = $timezone;
            }
            // 可选：设置全局应用时区
            //Yii::$app->setTimeZone($timezone);
        }
    }

    /**
     * 获取时间戳
     * @param $datetime
     * @param $timezone
     * @return int
     * @throws \Exception
     * @see DateTimeZone
     * @see DateTime
     */
    public static function getTimestamp($datetime, $timezone)
    {
        $timezone = new DateTimeZone($timezone);
        return (new DateTime($datetime, $timezone))->getTimestamp();
    }

    /**
     * @param $config
     * @return self
     */
    public static function getByContainer($config = [], $params = [])
    {
        try {
            return Yii::$container->get(self::class, $params, $config);
        } catch (NotInstantiableException|InvalidConfigException $e) {
            return new self($config);
        }
    }
}